package com.joymart.common.utils;

import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.common.model.Range;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class DatetimeUtils {

    private DatetimeUtils() {
    }

    /**
     * 有时候测试的时候，可以修改此处。实现全局时间的偏移
     * @return
     */
    public static LocalDateTime now(){
        return LocalDateTime.now();
    }

    public static Range month(LocalDateTime src) {
        LocalDateTime start = src.withDayOfMonth(1).with(LocalTime.MIN);
        LocalDateTime end = src.withDayOfMonth(src.toLocalDate().lengthOfMonth()).with(LocalTime.MAX);
        return Range.of(start, end);
    }

    public static Range year(LocalDateTime src) {
        LocalDateTime start = src.withDayOfYear(1).with(LocalTime.MIN);
        LocalDateTime end = src.withDayOfYear(src.toLocalDate().lengthOfYear()).with(LocalTime.MAX);
        return Range.of(start, end);
    }


    public static void checkRangeWithin(int rangeOfDays, Range range) {
        if(Duration.between(range.getStart(), range.getEnd()).toDays() > rangeOfDays){
            throw new JoymartBusinessException("时间区间不得大于%s天".formatted(rangeOfDays));
        }
    }
}
